# -*- coding: utf-8 -*-
import mimetypes
import os.path

from odoo import api, fields, models


class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    extension = fields.Char(string='File Extension', compute='_compute_extension')
    
    @api.depends('mimetype', 'store_fname')
    def _compute_extension(self):
        for attachment in self:
            if attachment.store_fname:
                attachment.extension = os.path.splitext(attachment.store_fname)[1]
            elif attachment.mimetype:
                attachment.extension = mimetypes.guess_extension(attachment.mimetype, strict=False)

    @api.model
    def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
        if not any(arg[0] in ('id', 'res_field') for arg in args):
            args.insert(0, ('res_field', '=', False))

        ids = super(models.Model, self)._search(args, offset=offset, limit=limit, order=order,
                                                count=False, access_rights_uid=access_rights_uid)

        if not ids:
            return 0 if count else []
        else:
            return len(ids) if count else ids